<?php
/**
 * 首页接口
 * Created by PhpStorm.
 * User: Earl <guo@seosite.cn>
 * Date: 2017/9/11
 * Time: 下午3:04
 * Updatetime:
 * updater：
 */

namespace App\Controller;


class HomeController extends BaseController
{

    /**
     * @desc 所有的汽车、分组数据列表综合
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function carListByGroup($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        unset($check);


        $model = M('car');

        $map['uid'] = $this->userInfo->id;

        if(!empty($param['keyword'])){//搜索

            $map['car_no'] = array('like','%'.$param['keyword'].'%');
            list($list,$page) = _listPage($model,$map,1,null,'id,gid,car_no,headsmall','1000');

            if (!empty($list)){
                foreach ($list as $k=>$v){
                    $list[$k]['_child'] = [];
                }
            }

        }else{
            list($list,$page) = _listPage($model,$map,1,'gid desc','group_concat(id) ids,gid','1000','gid');

            if (!empty($list)){
                foreach ($list as $k=>$v){
                    if (empty($v['gid'])){
                        foreach (explode(',',$v['ids']) as $key=>$val){
                            $list[$k+$key] = $model->field('id,gid,headsmall,car_no')->where(['id'=>$val])->find();
                            $list[$k+$key]['_child'] = [];
                        }
                    }else{
                        $list[$k]['id'] = '';

                        $list[$k]['gid'] = $v['gid'];//群的id


                        $list[$k]['headsmall'] = '';//群的图标
                        $list[$k]['car_no'] = M('car_group')->field('title')->where(['id'=>$v['gid']])->getField('title');

                        $list[$k]['_child'] = [];
                        foreach (explode(',',$v['ids']) as $key=>$val){
                            $list[$k]['_child'][$key] = $model->field('id,headsmall,car_no')->where(['id'=>$val])->find();
                            $list[$k]['_child'][$key]['_child'] = [];
                        }
                        unset($list[$k]['ids']);
                    }
                }
            }

            $all = $model->where($map)->field('id,gid,car_no,headsmall')->select();

            foreach ($all as $all_k => $all_v){
                $all[$all_k]['_child'] = [];
            }
            $first = [
                'id' => '',
                'gid'=> '',
                'car_no' => '全部设备',
                'headsmall'=>'',
                '_child'    =>  $all
            ];
            array_unshift($list,$first);
        }

        return showList($list,new \stdClass());
    }


    /**
     * @desc 实时汽车数据列表
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function nowData($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        unset($check);

        $p = empty($param['p']) ?: $param['p'];
        $listRows = empty($param['listRows']) ? 20 : $param['listRows'];

        $model = M('car');

//        if (!empty($param['keyword'])){
//            $where['c.car_no'] = array('like','%'.$param['keyword'].'%');
//            $where['c.container_no'] = array('like','%'.$param['keyword'].'%');
//            $where['_logic'] = 'or';
//            $map['_complex'] = $where;
//        }
//
//        $map['c.uid'] = $this->userInfo->id;
//        $map['c.status'] = 3;
//
//        $join = "left join think_car_attr a on c.id = a.car_id ";
//
//        list($list,$page) = _listPage($model,$map,$p,null,"c.id,c.car_no,c.equipment_no,c.last_call_time,a.speed,a.id car_attr_id,a.electric,a.voltage,a.cold_switch,a.humidity,a.temperature_one,a.temperature_two,a.temperature_three,a.temperature_four,concat(left(a.oil/c.oil_volume * 100,5),'%') oil_percents,a.humidity_one,a.humidity_two,a.humidity_three,a.humidity_four",$listRows,null,$join);

        if (!empty($param['keyword'])){
            $where['car_no'] = array('like','%'.$param['keyword'].'%');
            $where['container_no'] = array('like','%'.$param['keyword'].'%');
            $where['_logic'] = 'or';
            $map['_complex'] = $where;
        }

        $map['uid'] = $this->userInfo->id;
        $map['status'] = 3;

//        $join = "left join think_car_attr a on c.id = a.car_id ";

        list($list,$page) = _listPage($model,$map,$p,null,"id,car_no,equipment_no,last_call_time",$listRows);


        $model_attr = M('car_attr');
        if (!empty($list)){
            foreach ($list as $k=>$v){

                $attrInfo = $model_attr->where(['car_id'=>$v['id']])->order('id desc')->find();
                $list[$k]['speed'] = $attrInfo['speed'];
                $list[$k]['car_attr_id'] = $attrInfo['id'];
                $list[$k]['electric'] = $attrInfo['electric'];
                $list[$k]['voltage'] = $attrInfo['voltage'];
                $list[$k]['cold_switch'] = $attrInfo['cold_switch'];
                $list[$k]['humidity'] = $attrInfo['humidity'];
                $list[$k]['temperature_one'] = $attrInfo['temperature_one'];
                $list[$k]['temperature_two'] = $attrInfo['temperature_two'];
                $list[$k]['temperature_three'] = $attrInfo['temperature_three'];
                $list[$k]['temperature_four'] = $attrInfo['temperature_four'];
                $list[$k]['oil_percents'] = $attrInfo['oil'];
                $list[$k]['humidity_one'] = $attrInfo['humidity_one'];
                $list[$k]['humidity_two'] = $attrInfo['humidity_two'];
                $list[$k]['humidity_two'] = $attrInfo['humidity_two'];
                $list[$k]['humidity_three'] = $attrInfo['humidity_three'];
                $list[$k]['humidity_four'] = $attrInfo['humidity_four'];
                $list[$k]['lng'] = $attrInfo['lng'];
                $list[$k]['lat'] = $attrInfo['lat'];



            }
        }

        $model_config = M('system_config');

        $user_config = $model_config->where(['uid'=>$this->userInfo->id])->find();


        if (!empty($list)){
            foreach ($list as &$v){

                $v['speed_normal'] = $v['speed']<20 || $v['speed']>110 ? 2:1;
                $v['electric_normal'] = $v['electric_normal']<13 ? 2:1;
                $v['oil_percents_normal'] = $v['oil_percents']<25 ? 2:1;
                $v['temperature_one_normal'] = $v['temperature_one']<20 ? 2:1;
                $v['temperature_two_normal'] = $v['temperature_two']<20 ? 2:1;
                $v['temperature_three_normal'] = $v['temperature_three']<20 ? 2:1;
                $v['temperature_four_normal'] = $v['temperature_four']<20 ? 2:1;

                //速度
                if (empty($user_config) || $user_config['speed']==1){
                    $v['speed_unit'] = 'km/h';
                }else{
                    $v['speed'] = 0.62 * $v['speed'];
                    $v['speed_unit'] = 'mi/h';
                }

                //温度
                if (empty($user_config) || $user_config['temperature'] == 1){
                    $v['temperature_one_unit'] = '℃';
                    $v['temperature_two_unit'] = '℃';
                    $v['temperature_three_unit'] = '℃';
                    $v['temperature_four_unit'] = '℃';
                }else{
                    $v['temperature_one'] = (9 * $v['temperature_one']/5)+32;
                    $v['temperature_one_unit'] = '℉';

                    $v['temperature_two'] = (9 * $v['temperature_two']/5)+32;
                    $v['temperature_two_unit'] = '℉';

                    $v['temperature_three'] = (9 * $v['temperature_three']/5)+32;
                    $v['temperature_three_unit'] = '℉';

                    $v['temperature_four'] = (9 * $v['temperature_four']/5)+32;
                    $v['temperature_four_unit'] = '℉';
                }
            }
        }

        return showList($list,$page);
    }


    /**
     * @desc 修改汽车属性
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function carAttrUpdate($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('car_id,car_attr_id');

        unset($check);

        $model = M('car');
        $model_attr = M('car_attr');

        if (!empty($param['sec'])){
            $save_data_c = [
                'id'    =>  $param['car_id'],
                'callback_sec'  =>  $param['sec']
            ];
            $model->save($save_data_c);
        }

        $save_data_a['id'] = $param['car_attr_id'];
        if (!empty($param['temperature_one_area'])) $save_data_a['temperature_one_area'] = $param['temperature_one_area'];
        if (!empty($param['temperature_two_area'])) $save_data_a['temperature_two_area'] = $param['temperature_two_area'];
        if (!empty($param['temperature_three_area'])) $save_data_a['temperature_three_area'] = $param['temperature_three_area'];
        if (!empty($param['temperature_four_area'])) $save_data_a['temperature_four_area'] = $param['temperature_four_area'];
        if (!empty($param['humidity_one'])) $save_data_a['humidity_one'] = $param['humidity_one'];
        if (!empty($param['humidity_two'])) $save_data_a['humidity_two'] = $param['humidity_two'];
        if (!empty($param['humidity_three'])) $save_data_a['humidity_three'] = $param['humidity_three'];
        if (!empty($param['humidity_four'])) $save_data_a['humidity_four'] = $param['humidity_four'];
        $model_attr->save($save_data_a);

        return showErrorMsg(L("_OPERATION_SUCCESS_"));
    }

    /**
     * @desc 汽车数据详情
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function carDataInfo($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('car_id');

        unset($check);


        $model = M('car c');


//        $info = $model->field('id,car_no,last_call_time,status')->where(['id'=>$param['car_id']])->find();





        $info = $model->join("left join think_car_attr a on c.id = a.car_id")->field('c.id,c.car_no,c.last_call_time,a.speed,a.id car_attr_id,c.status,a.voltage,a.electric,a.stop_time status_time,a.temperature_one,a.temperature_two,a.temperature_three,a.temperature_four,a.humidity_one,a.humidity_two,a.humidity_three,a.humidity_four,a.today_mileage,a.lng,a.lat,a.electric,a.humidity,a.stop_time,a.create_time')->where(['c.id'=>$param['car_id']])->order('a.id desc')->find();


        $model_config = M('system_config');

        $user_config = $model_config->where(['uid'=>$this->userInfo->id])->find();


        //速度
        if (empty($user_config) || $user_config['speed']==1){
            $info['speed_unit'] = 'km/h';
        }else{
            $info['speed'] = 0.62 * $info['speed'];
            $info['speed_unit'] = 'mi/h';
        }

        //停车时间

        if (!empty($info['status_time'])){
            $info['status_time']=round($info['status_time']/60);
        }

        //温度
        if (empty($user_config) || $user_config['temperature'] == 1){
            $info['temperature_one_unit'] = '℃';
            $info['temperature_two_unit'] = '℃';
            $info['temperature_three_unit'] = '℃';
            $info['temperature_four_unit'] = '℃';
        }else{
            $info['temperature_one'] = round((9 * $info['temperature_one']/5)+32);
            $info['temperature_one_unit'] = '℉';

            $info['temperature_two'] = round((9 * $info['temperature_two']/5)+32);
            $info['temperature_two_unit'] = '℉';

            $info['temperature_three'] = round((9 * $info['temperature_three']/5)+32);
            $info['temperature_three_unit'] = '℉';

            $info['temperature_four'] = round((9 * $info['temperature_four']/5)+32);
            $info['temperature_four_unit'] = '℉';
        }

        $info['today_mileage']=round($info['today_mileage']/1000,2);


        return showErrorMsg(L("_OPERATION_SUCCESS_"),0,2,$info);

    }


    /**
     * @desc 定位地图列表
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function carMapList($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        unset($check);

        $p = empty($param['p']) ?: $param['p'];

        $model = M('car');

        if (!empty($param['keyword'])){
            $map['car_no'] = array('like','%'.$param['keyword'].'%');
        }

        $map['uid'] = $this->userInfo->id;
        $map['status'] = 3;

        $listRows = $model->where($map)->count();

        list($list,$page) = _listPage($model,$map,$p,null,"id,car_no",$listRows);

        if (!empty($list)){
            foreach ($list as $k=>$v){
                $info = M('car_attr')->where(['car_id'=>$v['id']])->order('id desc')->find();
                $list[$k]['lng'] = $info['lng'];
                $list[$k]['lat'] = $info['lat'];
                $list[$k]['create_time'] = $info['create_time'];
            }
        }


        return showList($list,$page);
    }

    /**
     * @desc 查看历史轨迹
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function carHistoryLocation($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('car_id,s_time,e_time');

        unset($check);

        $model = M('car_location_record');

        $map['uid'] = $this->userInfo->id;
        $map['car_id'] = $param['car_id'];
        $map['create_time'] = array('between',array(strtotime($param['s_time']),strtotime($param['e_time'])));

        $list = $model->where($map)->select();

        return showList($list,new \stdClass());

    }

    /**
     * @desc 是否有未读消息
     * @author Egor<http://gitee.com/seosite>
     * @param $param
     * @return array
     */
    public function isUnReadMsg($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        unset($check);

        $model = M('message');

        $map['uid'] = $this->userInfo->id;
        $map['is_read'] = 0;

        $is_unread = $model->where($map)->find();

        return showErrorMsg(L("_OPERATION_SUCCESS_"),0,2,['unread'=>!empty($is_unread)?1:0]);
    }


    /**
     * @desc 路线导航
     * @param $param
     * @return array
     * @author Egor<http://gitee.com/seosite>
     */
    public function routeTrajectory($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('s_lat,s_lng,e_lat,e_lng');

        unset($check);

        $url ='https://maps.googleapis.com/maps/api/directions/json?origin='.$param['s_lng'].','.$param['s_lat'].'&destination='.$param['e_lng'].','.$param['e_lat'].'&sensor=false&mode=driving';
//        $url ='https://maps.googleapis.com/maps/api/directions/json?origin=31.2894068447,121.5202903748&destination=31.3057689809,121.4807650411&sensor=false&mode=driving';

        $contents = file_get_contents($url);

        $contents = json_decode($contents,true);

        if ($contents['status'] !== 'OK') return showErrorMsg('输入信息有误，请重新尝试！',100002);

        $ret_data = $contents['legs'];

        return showErrorMsg(L('_OPERATION_SUCCESS_'),0,2,$ret_data);
    }

    /**
     * @desc 发送CMD命令消息
     * @param $param
     * @return array
     * @author Egor<http://gitee.com/seosite>
     */
    public function sendCmdMsg($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        $check = CheckFactoryController::isParamSet();
        $check->before($param);

        $check = CheckFactoryController::isChildParamSet();
        $check->before('type,car_no,content');

        unset($check);

        $car_id = M('car')->where(['car_no'=>$param['car_no']])->getField('id');

        $insert_data = [
            'uid'   =>  $this->userInfo->id,
        'send_uid'  =>  $this->userInfo->id,
            'title' =>  empty($param['title'])?'':$param['title'],
            'content'   =>  empty($param['content'])?'':$param['content'],
            'is_read'   =>  0,
            'type'  =>  empty($param['type'])?1:$param['type'],
            'car_id'    =>  empty($car_id)?'':$car_id,
            'warning_type'  =>  empty($param['warning_type'])?'':$param['warning_type']
        ];

        M('message')->add($insert_data);

        return showErrorMsg(L("_OPERATION_SUCCESS_"));
    }


    public function getUserList()
    {
        $list = M('user')->field('id,username')->select();

        return showList($list,new \stdClass());
    }

    public function getCarList()
    {
        $map['uid'] = $this->userInfo->id;

        $list = M('car')->field('id,car_no')->where($map)->select();

        return showList($list,new \stdClass());
    }


    /**
     * @desc 首页更新时间
     * @param $param
     * @return array
     * @author Egor<http://gitee.com/seosite>
     */
    public function getRefreshTime($param)
    {
        $check = CheckFactoryController::isLogin();
        $check->before($param);

        unset($check);

        $model = M('system_config');

        $systemInfo = $model->where(['uid'=>$this->userInfo->id])->find();

        $refresh_time = empty($systemInfo) ? 0 : $systemInfo['refresh_time'];

        return showErrorMsg(L("_OPERATION_SUCCESS_"),0,2,['time'=>$refresh_time]);
    }
}